package 实验五;


import week4.homework.RationalNumber;

import java.util.Stack;
import java.util.StringTokenizer;
// 后缀表达式求值
public class    MyDC {
    Stack<String> stack = new Stack<String>();

    RationalNumber num1,num2,num3;

    public MyDC() {
        stack = new Stack<String>();
    }

    public String calculator(String q)
    {
        String op1, op2, result;
        String a;
        StringTokenizer tokenizer = new StringTokenizer(q);

        while (tokenizer.hasMoreTokens())
        {
            a = tokenizer.nextToken();

            if(a.equals("+") || a.equals("-") || a.equals("*") || a.equals("÷"))
            {
                // 把栈顶的操作数弹出，转换为RationalNumber类型
                op2 = stack.pop();
                num2 = conToRantionalNum(op2);

                // 继续把栈顶的操作数弹出，转换为RationalNumber类型
                op1 = stack.pop();
                num1 = conToRantionalNum(op1);

                //计算结果
                result = calculate(num1,a.charAt(0),num2);
                stack.push(result.toString());
            }
            else {
                stack.push(a);
            }
        }
        result = stack.pop();
        return result;
    }

    public RationalNumber conToRantionalNum (String a)
    {
        String numer,denom;  // numer分子，denom分母


        //  把分数a/b以"/"为标记分割开
        StringTokenizer tokenizer1 = new StringTokenizer(a,"/");
        numer = tokenizer1.nextToken();
        if (tokenizer1.hasMoreTokens())
        //  如果分母不为1
        {
            denom = tokenizer1.nextToken();
            num1 = new RationalNumber(Integer.parseInt(numer), Integer.parseInt(denom));
        }
        else
        //  如果分母为1
        {
            num1 = new RationalNumber(Integer.parseInt(numer), 1);
        }
        return num1;
    }

    // 计算+、-、*、÷
    public String calculate(RationalNumber op1, char operation, RationalNumber op2)
    {
        RationalNumber result = new RationalNumber(0,1);

        switch (operation)
        {
            case '+':
                result = op1.add(op2);
                break;
            case '-':
                result = op1.subtract(op2);
                break;
            case '*':
                result = op1.multiply(op2);
                break;
            case '÷':
                result = op1.divide(op2);
                break;
        }
        return result.toString();
    }
}



